import 'package:flutter/material.dart';
import 'dart:ui' as ui;

// https://juejin.cn/post/7205546336081952828
class ImageClipper extends CustomPainter {
  final ui.Image image;
  // 0 <= x <= 1
  final double x;
  final double y;
  // 0 <= y <= 1
  // 需要裁剪的比例
  final double ratio;
  ImageClipper(
    this.image, {
    this.x = 0.0,
    this.y = 0.0,
    this.ratio = 0.75,
  });
  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    final imageSourceWidth = image.width;
    final imageSourceHeight = image.height;
    Rect src = Rect.fromLTWH(
        0, 0, imageSourceWidth.toDouble(), imageSourceHeight.toDouble());
    // 超长异形图
    if (imageSourceHeight / imageSourceWidth > 3.0) {
      final l = x * imageSourceWidth;
      final w = imageSourceWidth;
      final h = imageSourceWidth / ratio;
      double t = y * (imageSourceHeight - h);
      src = Rect.fromLTWH(l, t, w.toDouble(), h.toDouble());
    }
    // 超宽
    if (imageSourceWidth / imageSourceHeight > 3.0) {
      double t = y * imageSourceHeight;
      final h = imageSourceHeight;
      final w = imageSourceWidth * ratio;
      double l = x * (imageSourceWidth - w);
      if (l + w > imageSourceWidth) {
        l = 0;
      }
      src = Rect.fromLTWH(l, t, w.toDouble(), h.toDouble());
    }
    canvas.drawImageRect(
        image, src, Rect.fromLTWH(0, 0, size.width, size.height), paint);
  }
}
